package com.pzb.order.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pzb.common.core.domain.AjaxResult;
import com.pzb.common.utils.StringUtils;
import com.pzb.goods.domain.GdGoods;
import com.pzb.goods.service.IGdGoodsService;
import com.pzb.market.domain.MkDiscount;
import com.pzb.market.service.IMkDiscountService;
import com.pzb.order.domain.*;
import com.pzb.order.service.IOdOrderDetailService;
import com.pzb.order.service.IOdOrderSettingService;
import com.pzb.rabbitmq.RabbitMqModel;
import com.pzb.rabbitmq.RabbitMqSender;
import com.pzb.wechat.domain.WechatUserAccount;
import com.pzb.wechat.service.IWechatUserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pzb.order.mapper.OdOrderMapper;
import com.pzb.order.service.IOdOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单管理Service业务层处理
 * 
 * @author Mr_Wu
 * @date 2021-12-15
 */
@Service
public class OdOrderServiceImpl implements IOdOrderService 
{
    @Autowired
    private OdOrderMapper odOrderMapper;

    @Autowired
    private IOdOrderDetailService orderDetailService;
    @Autowired
    private IMkDiscountService discountService;
    @Autowired
    private IGdGoodsService gdGoodsService;
    @Autowired
    private IOdOrderSettingService orderSettingService;
    @Autowired
    private RabbitMqSender rabbitMqSender;
    @Autowired
    private IWechatUserAccountService userAccountService;

    /**
     * 查询订单管理
     * 
     * @param id 订单管理主键
     * @return 订单管理
     */
    @Override
    public OdOrder selectOdOrderById(Long id)
    {
        OdOrder order = odOrderMapper.selectOdOrderById(id);
        if (StringUtils.isNotBlank(order.getAreaCode())) {
            order.setAreaCodeArray(JSON.parseArray(order.getAreaCode()));
        }
        return order;
    }

    /**
     * 查询订单管理列表
     * 
     * @param odOrder 订单管理
     * @return 订单管理
     */
    @Override
    public List<OdOrder> selectOdOrderList(OdOrder odOrder)
    {
        return odOrderMapper.selectOdOrderList(odOrder);
    }

    /**
     * 修改订单管理
     * 
     * @param odOrder 订单管理
     * @return 结果
     */
    @Override
    public int updateOdOrder(OdOrder odOrder)
    {
        if(odOrder.getAreaCodeArray()!=null){
            odOrder.setAreaCode(odOrder.getAreaCodeArray().toString());
            String fullAddress = "";
            for (Object address : odOrder.getAreaCodeArray()) {
                JSONObject a = (JSONObject) JSONObject.toJSON(address);
                fullAddress+= a.getString("label");
            }
            odOrder.setFullAddress(fullAddress+odOrder.getAddress());
        }
        return odOrderMapper.updateOdOrder(odOrder);
    }

    @Override
    public OdOrder selectOrderDetailById(Long id) {
        OdOrder order = odOrderMapper.selectOdOrderById(id);
        //查询赠品
        if(order.getDiscountId()!=null && order.getDiscountId().longValue()>0){
            MkDiscount discount = discountService.selectMkDiscountById(order.getDiscountId());
            //如果是送赠品
            if("3".equals(discount.getType())){
                List<GdGoods> giftList = gdGoodsService.selectGiftListByDiscountId(discount.getId());
                discount.setGiftList(giftList);
                order.setDiscount(discount);
            }
        }
        List<OdOrderDetail> orderDetailList = orderDetailService.selectOdOrderDetailByOrderCode(order.getOrderCode());
        order.setOrderDetailList(orderDetailList);
        return order;
    }

    @Override
    public OdOrder selectOdOrderByOrderCode(String orderCode) {
        return odOrderMapper.selectOdOrderByOrderCode(orderCode);
    }

    //订单发货
    @Override
    public int sendGoods(OdOrder odOrder) {
        //如果是自提  订单已完成
        if("1".equals(odOrder.getDeliveryMethod())){
            odOrder.setOrderStatus("2");
            odOrder.setDeliveryTime(new Date());
            odOrder.setFinishTime(new Date());
        }else if("0".equals(odOrder.getDeliveryMethod())){
            odOrder.setOrderStatus("1");
            odOrder.setDeliveryTime(new Date());
            //查询订单设置
            OdOrderSetting setting = orderSettingService.selectOdOrderSetting(odOrder.getExtAppid());
            //发送自动收货消息队列
            RabbitMqModel mqModel = new RabbitMqModel();
            mqModel.setType(1);
            mqModel.setOrderNo(odOrder.getOrderCode());
            rabbitMqSender.sendMessage(mqModel,setting.getReceivingDays()*24*60*60*1000);
        }
        return odOrderMapper.updateOdOrder(odOrder);
    }

    //同意取消订单
    @Override
    @Transactional
    public int cancelOrder(Long id) {
        OdOrder order = odOrderMapper.selectOdOrderById(id);
        order.setOrderStatus("5");
        WechatUserAccount userAccount = userAccountService.selectWechatUserAccountByOpenId(order.getOpenid(),order.getExtAppid());
        //再次确认付款状态
        if(("1").equals(order.getPayStatus())){//退款
            userAccount.setBalance(String.valueOf(new BigDecimal(userAccount.getBalance()).add(new BigDecimal(order.getPayTotalAmount()))));
        }
        //退积分
        if(order.getIntegral().longValue()>0){
            //退积分
            userAccount.setIntegral(userAccount.getIntegral()+order.getIntegral().intValue());
        }
        userAccountService.updateWechatUserAccount(userAccount);
        return odOrderMapper.updateOdOrder(order);
    }

    /**
     * 首页数据汇总
     * @param extAppid
     * @return
     */
    @Override
    public AjaxResult orderDataCount(String extAppid) {
        //统计数据
        OrderCountModel countModel = odOrderMapper.selectOrderCount(extAppid);
        if(countModel.getSaleToday() == null){
            countModel.setSaleToday(0.00);
        }
        if(countModel.getSaleYesterday() == null){
            countModel.setSaleYesterday(0.00);
        }
        if(countModel.getSaleTotal() == null){
            countModel.setSaleTotal(0.00);
        }
        //近7日 订单数 销售额 汇总
        List<OrderChartModel> dataList = odOrderMapper.selectOrderChart(extAppid);
        List<String> dataTime =new ArrayList<>();
        List<String> dataSale =new ArrayList<>();
        List<Integer> dataOrder = new ArrayList<>();
        for (OrderChartModel orderChartModel : dataList) {
            dataTime.add(orderChartModel.getDataTime());
            dataSale.add(orderChartModel.getDataSale());
            dataOrder.add(orderChartModel.getDataOrder());
        }
        countModel.setDataTime(dataTime);
        countModel.setDataSale(dataSale);
        countModel.setDataOrder(dataOrder);
        return AjaxResult.success(countModel);
    }

}
